package edu.siu.math.egut.egut;

/** A class to check whether a string has matching parentheses. 
 * Handles multiple parenthesis shapes: (), []. */
public class MatchParen {
  
  /** This variable becomes false if we ever see a right parenthesis
   * whose corresponding left parenthesis is missing or of the wrong shape. 
   */
  private boolean matching;  

  /** A stack of all the left parentheses remaining to be matched. */
  private final java.util.Stack<Character> s ;  // 

 /**
 * Create a new instance of MatchParen
 */
public MatchParen (){

     matching = true;
     s = new java.util.Stack<Character>();
 }

  /** Returns true if the sequence of chars added so far 
   * makes up a string with balanced parentheses. 
 * @return true if the stack is empty and there have been no mismatched parens*/
  public boolean isMatching() {  
    return matching && s.isEmpty();
  }

  /** Add a single new character.  A user can add the
   * characters one at a time, and call isMatching after
   * each character to see whether there is an error yet. 
 * @param c char to add
   */ 

  public void add(char c) {  
    Character m = leftMatch(c);   // or use leftMatch2
    if (m == null)                // c is not a parenthesis
      ;                              // do nothing (i.e., ignore it)
    else if (m.charValue() == c)  // c is some kind of left parenthesis
      s.push(m);                     // push a Character version, m
    else {                        // c is some kind of right paren
      if (s.isEmpty() || !s.pop().equals(m))  
	matching = false;            // couldn't pop a matching left paren, m
    }
  }

  

  

  private static Character leftMatch(char c) {
    switch (c) {
    case '(': 
    case ')':
      return new Character('(');   
    case '[':
    case ']':
      return new Character('[');
    default:
      return null;
    }
  }





}
